package com.interceptor;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        String uri = httpServletRequest.getRequestURI();
        //判断当前请求地址是否为登入地址
        if(!(uri.contains("login") || uri.contains("Login"))){
            //非登入请求
            if(httpServletRequest.getSession().getAttribute("user") != null){
                //说明已经登入过，放行
                return true;
            }else{
                //没有登入，跳转到登入界面
                httpServletResponse.sendRedirect(httpServletRequest.getContextPath()+"/home/login");
            }
        }else{
            //登入请求，直接放行
            return true;
        }
        return false;   //默认拦截
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
